package com.sakiko.ioc_01;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.*;

@Component  // <bean id="userDao" class="com.sakiko......"
public class UserDao {

    @Autowired // ref="dataSource"
    private DruidDataSource dataSource;

    public void queryAll() throws SQLException {
        // 2、获取连接
        Connection connection = dataSource.getConnection();
        // 3、数据库 CRUD
        String sql = "select * from sys_user;";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        // metaData 包含列的信息 列的数量: ColumnCount 列名: ColumnName
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (resultSet.next()) {
            for (int i = 1; i <= columnCount; i++) {
                String value = resultSet.getString(i); // ColumnIndex or ColumnLabel
                String columnName = metaData.getColumnName(i);
                System.out.println(columnName + "::" + value + " ");
            }
            System.out.println("-----------------------");
        }
        // 4、释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
